# coding=utf-8
from abc import ABCMeta
import tornado.web
import tornado.escape
import json

from CommonLib import CheckJsonKeys, CheckAuth
from database.models.DatabaseCommon import *
from database.models.Normal import Normal
from database.models.OperationSet import OperationSet
import WrapCursor


class InsNormalStepHandler(tornado.web.RequestHandler):
    __metaclass__ = ABCMeta

    def post(self):
        ojson = None
        r = WrapCursor.WrapCursor()
        try:
            ojson = json.loads(self.request.body)
            desc = ojson['normalID']
            data = ojson['data']
            step = data[0]
            tmp = step['PointID']
            tmp = step['Opt']
            tmp = step['Params']
            CheckJsonKeys(ojson, 'username', 'userpass')
            CheckAuth(ojson)
        except Exception as e:
            self.write(r.Error(u'请求数据错误 :' + str(e.message)))
            return

        s = Session()
        normalID = ojson['normalID']
        nc = s.query(Normal).filter_by(id=normalID).all()
        if len(nc) is not 1:
            self.write(r.Error(u'模式不存在'))
            return
        data = ojson['data']

        for i in data:
            step = OperationSet(PointID=i['PointID'], OptTypeID=i['Opt'], Params=i['Params'],NormalID=normalID)
            s.add(step)
        try:
            s.commit()
        except Exception as e:
            self.write(r.Error(u'失败:增加模式动作失败'))
            return
        self.write(r.Ok(u'成功'))
        return
